"use strict"
var program = require('commander')
var fs = require('fs')
var path = require('path')
var fstream = require('fstream')
var tar = require('tar')

function rmDir(dir) {
  if (fs.existsSync(dir)) {
    let files = fs.readdirSync(dir)
    files.forEach(function(file, index) {
      let curPath = path.join(dir, `/${file}`)
      if (fs.statSync(curPath).isDirectory()) {
        rmDir(curPath)
      } else {
        fs.unlinkSync(curPath)
      }
    })
    fs.rmdirSync(dir)
  }
}
exports.rmDir = rmDir

function copyFile(dstFile, srcFile) {
  var readable = fs.createReadStream(srcFile)
  var writable = fs.createWriteStream(dstFile)  
  readable.pipe(writable)
}
exports.copyFile = copyFile

function copyDir(dst, src) {
  if (fs.existsSync(src)) {
    let files = fs.readdirSync(src)
    files.forEach(function(file, index) {
      let srcPath = path.join(src, `/${file}`)
      let dstPath = path.join(dst, `/${file}`)
      if (fs.statSync(srcPath).isDirectory()) {
        fs.mkdirSync(dstPath)
        copyDir(dstPath, srcPath)
      } else {
        copyFile(dstPath, srcPath)
      }
    })
  }
}
exports.copyDir = copyDir

function tarDir(srcDir, dstFile) {
  fstream.Reader({
    path: srcDir,
    type: 'Directory'
  }).pipe(tar.Pack())
  .pipe(fstream.Writer({
    path: dstFile
  }))  
}
exports.tarDir = tarDir